import 'dart:io';

import 'package:example/pages/excel/controller.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold_ohos/common/index.dart';
import 'package:path_provider/path_provider.dart';
import 'package:excel/excel.dart';

class ExcelPage extends GetView<ExcelController>{
  const ExcelPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ExcelController>(
      init: ExcelController(),
      id: 'Excel',
      builder: (_){
        return Scaffold(
          appBar: AppBar(
            title: const Text('Excel Demo'),
            centerTitle: true,
            elevation: 1,
          ),
          body: Container(
            width: double.infinity,
            height: double.infinity,
            child: Column(
              children: [
                ListTile(
                  title: const Text('导入Excel'),
                  onTap: () async{
                    var directory = await getDownloadsDirectory();
                    var file = '${directory!.path}/output_file_name1.xlsx';
                    var bytes = File(file).readAsBytesSync();
                    var excel = Excel.decodeBytes(bytes);
                    for (var table in excel.tables.keys) {
                      print(table); //sheet Name
                      print(excel.tables[table]);
                      // for (var row in excel.tables[table].rows) {
                      //   for (var cell in row) {
                      //     print('cell ${cell.rowIndex}/${cell.columnIndex}');
                      //     // final value = cell.value;
                      //     // final numFormat = cell.cellStyle?.numberFormat ?? NumFormat.standard_0;
                      //     // switch(value){
                      //     //   case null:
                      //     //     print('  empty cell');
                      //     //     print('  format: ${numFormat}');
                      //     //   case TextCellValue():
                      //     //     print('  text: ${value.value}');
                      //     //   case FormulaCellValue():
                      //     //     print('  formula: ${value.formula}');
                      //     //     print('  format: ${numFormat}');
                      //     //   case IntCellValue():
                      //     //     print('  int: ${value.value}');
                      //     //     print('  format: ${numFormat}');
                      //     //   case BoolCellValue():
                      //     //     print('  bool: ${value.value ? 'YES!!' : 'NO..' }');
                      //     //     print('  format: ${numFormat}');
                      //     //   case DoubleCellValue():
                      //     //     print('  double: ${value.value}');
                      //     //     print('  format: ${numFormat}');
                      //     //   case DateCellValue():
                      //     //     print('  date: ${value.year} ${value.month} ${value.day} (${value.asDateTimeLocal()})');
                      //     //   case TimeCellValue():
                      //     //     print('  time: ${value.hour} ${value.minute} ... (${value.asDuration()})');
                      //     //   case DateTimeCellValue():
                      //     //     print('  date with time: ${value.year} ${value.month} ${value.day} ${value.hour} ... (${value.asDateTimeLocal()})');
                      //     // }
                      //
                      //     print('$row');
                      //   }
                      // }
                    }
                    // try {
                    //   // 打印path
                    //   var directory = await getApplicationDocumentsDirectory();
                    //   print("getApplicationDocumentsDirectory: " +
                    //       directory.path);
                    //   var directory1 = await getTemporaryDirectory();
                    //   print("getTemporaryDirectory: " + directory1.path);
                    //   var directory2 = await getApplicationSupportDirectory();
                    //   print(
                    //       "getApplicationSupportDirectory: " + directory2.path);
                    //
                    //   var directory4 = await getApplicationCacheDirectory();
                    //   print("getApplicationCacheDirectory: " + directory4.path);
                    //   var directory5 = await getExternalStorageDirectory();
                    //   print("getExternalStorageDirectory: " + directory5!.path);
                    //   var directory6 = await getExternalCacheDirectories();
                    //   directory6?.forEach((element) {
                    //     print("getExternalCacheDirectories: " + element.path);
                    //   });
                    //   var directory7 = await getExternalStorageDirectories();
                    //   directory7?.forEach((element) {
                    //     print("getExternalStorageDirectories: " + element.path);
                    //   });
                    //   var directory8 = await getDownloadsDirectory();
                    //   print("getDownloadsDirectory: " + directory8!.path);
                    // } catch (e) {
                    //   print(e);
                    // }
                  },
                ),
                ListTile(
                  title: const Text('导出Excel'),
                  onTap: () async{
                    var excel = Excel.createExcel();
                    const defaultSheetName = 'Sheet1';
                    const testSheetToKeep = 'Sheet To Keep';
                    const testSheetToKeepRename = 'Rename Of Sheet To Keep';

                    var listDynamic = (List<List<dynamic>>.generate(
                        5, (_) => List<int>.generate(5, (i) => i + 1))
                      ..insert(0, [
                        'A',
                        'B',
                        'C',
                        'D',
                        'E',
                      ]));

                    for (var row = 0; row < listDynamic.length; row++) {
                      for (var column = 0; column < listDynamic[row].length; column++) {
                        final cellIndex = CellIndex.indexByColumnRow(
                          columnIndex: column,
                          rowIndex: row,
                        );
                        var colorList = List.of(ExcelColor.values);


                        final string = listDynamic[row][column].toString();

                        var cellValue = int.tryParse(string) != null
                            ? IntCellValue(int.parse(string))
                            : TextCellValue(string);

                        excel.updateCell(
                          testSheetToKeep,
                          cellIndex,
                          cellValue,
                          cellStyle: CellStyle()
                            ..backgroundColor = (colorList..shuffle()).first
                            ..fontColor = (colorList..shuffle()).first
                            ..fontFamily = 'Arial',
                        );
                      }
                    }

                    ///
                    assert(excel.sheets.keys.contains(defaultSheetName));
                    assert(excel.getDefaultSheet() == defaultSheetName);
                    excel.delete(excel.getDefaultSheet()!);
                    assert(!excel.sheets.keys.contains(defaultSheetName));

                    ///
                    excel.rename(testSheetToKeep, testSheetToKeepRename);
                    excel.setDefaultSheet(testSheetToKeepRename);
                    assert(excel.getDefaultSheet() == testSheetToKeepRename);

                    final bytes = excel.save();
                    var directory = await getDownloadsDirectory();
                    if (bytes != null) {
                      File('${directory!.path}/output_file_name1.xlsx')
                        ..createSync()
                        ..writeAsBytesSync(bytes);
                      print('${directory.path}/output_file_name1.xlsx');
                    }
                  },
                )
              ],
            ),
          ),
        );
      },
    );
  }

}